package cn.hftoday.db;

import java.sql.*;
import java.util.*;

/**
 * Resultset from database
 * @author lane.cn@gmail.com
 * 
 */
public class RecordSet {
	private ResultSetMetaData rsmd = null;
	private List<Map<String, String>> rows = null;
	private String[] columns = null;
	
	/**
	 * resultset row count
	 * @return
	 */
	public int getRowCount() {
		return this.rows.size();
	}
	
	/**
	 * resultset row list
	 * @return
	 */
	public List<Map<String, String>> getRowList() {
		return rows;
	}

	/**
	 * resultset column count
	 * @return
	 */
	public int getColumnCount() {
		return this.columns.length;
	}

	/**
	 * column name
	 * @param index
	 * @return
	 */
	public String getColumnName(int index) {
		if (index >= getColumnCount() || index < 0) {
			throw new RuntimeException("error.rs.no.such.column.index");
		}
		return this.columns[index];
	}

	/**
	 * element value
	 * @param row
	 * @param column
	 * @return
	 */
	public String getItem(int row, int column) {
		return this.getItem(row, getColumnName(column));
	}

	/**
	 * element value
	 * @param row
	 * @param column
	 * @return
	 */
	public String getItem(int row, String column) {
		if (row >= rows.size() || row < 0) {
			throw new RuntimeException("error.rs.no.such.row.index");
		}
		Map<String, String> r = this.rows.get(row);
		if (!r.containsKey(column.toLowerCase())) {
			throw new RuntimeException("error.rs.no.such.column.name");
		}
		Object o = r.get(column.toLowerCase());
		if (o == null) {
			return null;
		}
		return o.toString();
	}

	/**
	 * init resultset
	 * @param rs
	 */
	public void setResultSet(ResultSet rs) {
		initColumn(rs);
		initRow(rs);
	}
	
	private void initColumn(ResultSet rs) {
		try {
			this.rsmd = rs.getMetaData();
			int count = rsmd.getColumnCount();
			this.columns = new String[count];
			for (int i = 0; i < count; i ++) {
				this.columns[i] = rsmd.getColumnName(i + 1).toLowerCase();
			}
		} catch (Exception e) {
			throw new RuntimeException("error.rs.init.column", e);
		}
	}
	
	private void initRow(ResultSet rs) {
		this.rows = new ArrayList<Map<String, String>>();
		try {
			while (rs.next()) {
				Map<String, String> row = new HashMap<String, String>();
				for (int i = 0; i < this.columns.length; i ++) {
					String value = rs.getString(i + 1);
					row.put(this.columns[i], value);
				}
				this.rows.add(row);
			}
		} catch (Exception e) {
			throw new RuntimeException("error.rs.init.row", e);
		}
	}
}
